package com.blindnews.controller;

import com.alibaba.fastjson.JSONObject;
import com.blindnews.pojo.Result;
import com.blindnews.service.impl.VoiceRecognitionService;
import com.blindnews.utils.AipClient;
import com.blindnews.utils.PagesSkip;
import com.blindnews.utils.VoiceSwitch;
import com.blindnews.utils.VolumeAdjust;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@Slf4j
public class VoiceController {

    private final String FORMAT = "wav";   //语音文件后缀

    private final String FPATH =  System.getProperty("user.dir");
    @Autowired
    private VoiceRecognitionService voiceRecognitionService;
    @Autowired
    private VolumeAdjust volumeAdjust;
    @Autowired
    private PagesSkip pagesSkip;
    @Autowired
    private  VoiceSwitch voiceSwitch;

    @PostMapping("/getVoice")

    public Result getVoice(@RequestParam(name="audioFile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            try {
                FileOutputStream out = new FileOutputStream(file.getOriginalFilename());
                System.out.println(file.getName());
                out.write(file.getBytes());
                out.flush();
                out.close();
                System.out.println("音频文件上传成功！");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("上传失败");
                return Result.error("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("上传失败");
                return Result.error("上传失败," + e.getMessage());
            }
            System.out.println("上传成功");
//            转百度api服务识别接受到的音频
            return getResult();
        } else {
            System.out.println("上传失败");
            return Result.error("上传失败，因为语音文件是空的." );
        }
    }

    public Result getResult(){
        String filePathName = null;
        String fName = "audioData"+ "." + FORMAT;
        String fName2 = "audioData2"+ "." + FORMAT;
        filePathName = FPATH+"\\"+fName2;
        String sourcePath = FPATH+"\\"+fName;
        String targetPath = FPATH+"\\"+fName2;
        voiceSwitch.waveMaker(sourcePath, targetPath);

        System.out.println(filePathName);
        try {
            //识别语音,返回结果
            if(filePathName != null) {
                AipClient aipClient = new AipClient();
                JSONObject data = aipClient.getSynthesis(filePathName, FORMAT);
                File file = new File(filePathName);
                // 路径为文件且不为空则进行删除
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
                if (data.containsKey("err_no") && data.getInteger("err_no")==0) {
                    String _res = data.getJSONArray("result").getString(0);
                    if (_res != null) {
                        //转操作指令
                        return Result.success( "语音识别成功" , _res ,findKey(_res));
                    }
                }
                return Result.error("语音识别失败。");
            } else {
                return  Result.error("语音文件为空！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  Result.error("语音识别失败。");
        }
    }

    //解析参数
    private void splitParam(Map<String, Object> map){
        String[] commands = ((String) map.get("command")).split(",");
        List<String> list = new LinkedList<>();
        for (String command : commands) {
            list.add(command);
        }
        map.put("command",list);
    }
    private String findKey(String str){
        if( ((str.contains("高"))||(str.contains("大")))&&((str.contains("音量"))||(str.contains("声音")) )) {
            log.info("包含大音量");//true
            volumeAdjust.volumeAd("1");
            return null;
        }
        else if (  ((str.contains("低"))||(str.contains("小")))&&((str.contains("音量"))||(str.contains("声音"))) ){
            log.info("包含小音量");
            volumeAdjust.volumeAd("2");
            return null;
        } else if ( (str.contains("静音"))  ) {
            volumeAdjust.volumeAd("0");
            return null;
        } else if ( (str.contains("国内")) ) {
            pagesSkip.left("l1");
            return "l1";
        } else if ((str.contains("国外"))||(str.contains("国际"))) {
            pagesSkip.left("l2");
            return "l2";
        }else if ((str.contains("军事"))) {
            pagesSkip.left("l3");
            return "l3";
        }else if ((str.contains("播放"))&&!(str.contains("暂停"))&&!(str.contains("停止"))&&!(str.contains("恢复"))&&!(str.contains("继续"))) {
            if( (str.contains("一") )|| (str.contains("1"))){
                pagesSkip.left("play1");
                return "play1";
            }else if ( (str.contains("二")) || (str.contains("2") )){
                return "play2";
            }else if ( (str.contains("三")) || (str.contains("3") )){
                return "play3";
            }else if ( (str.contains("四")) || (str.contains("4") )){
                return "play4";
            }else if ( (str.contains("五")) || (str.contains("5") )){
                return "play5";
            }else if ( (str.contains("六")) || (str.contains("6") )){
                return "play6";
            }else if ( (str.contains("七")) || (str.contains("7") )){
                return "play7";
            }
            else if ( (str.contains("八")) || (str.contains("8") )){
                return "play8";
            }
            else if ( (str.contains("九")) || (str.contains("9") )){
                return "play9";
            }else if ( (str.contains("十")) || (str.contains("10") )){
                return "play10";
            }
            else{
                return null;
            }

        } else if ((str.contains("暂停"))) {
            return "paused";
        } else if (((str.contains("恢复"))||(str.contains("继续")))&&(str.contains("播放"))) {
            return "goahead";
        } else if ((str.contains("停止"))&&(str.contains("播放"))) {
            return "stop";
        } else if ( ((str.contains("今天")) ||(str.contains("新闻")))&&((str.contains("什么"))||(str.contains("哪些")) ) ) {
            return "tips";
        } else if ((str.contains("还有吗")) ||(str.contains("下一个"))||(str.contains("接着说")) ||(str.contains("下一条"))) {
            return "moretips";
        } else {
            log.info("不包含");
            return null;
        }
    }

}
